/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package vista;

import clases.AlmacenArticulo;
import clases.Articulo;
import clases.Categoria;
import com.alee.extended.list.CheckBoxListModel;
import com.alee.extended.list.WebCheckBoxList;
import com.alee.laf.button.WebButton;
import com.alee.laf.checkbox.WebCheckBox;
import com.alee.laf.label.WebLabel;
import com.alee.laf.panel.WebPanel;
import com.alee.laf.rootpane.WebFrame;
import com.alee.laf.scroll.WebScrollPane;
import com.alee.laf.table.WebTable;
import com.alee.laf.text.WebTextField;
import controlador.CtrlArticulo;
import controlador.CtrlCategoria;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Edder
 */
public class FrmArticulos extends WebFrame{
    private WebTextField txtBusqueda;
    private WebCheckBox chbInactivos;
    private WebCheckBoxList chbLstCategorias;
    private WebTable tblArticulos;
    private WebTable tblStocks;
    private WebButton btnAgregar, btnEditar, btnCerrar;
    
    private CtrlArticulo ctrlArticulo;
    private CtrlCategoria ctrlCategoria;
    
    FrmArticulos(){
        setTitle("Artículos");
        setDefaultCloseOperation(WebFrame.DISPOSE_ON_CLOSE);
        setSize(600,400);
        setShowResizeCorner(false);
        setShowMaximizeButton(false);
        initComponents();
        setLocationRelativeTo(null);
    }
    
    private void initComponents(){
        this.ctrlCategoria = new CtrlCategoria();
        this.ctrlArticulo = new CtrlArticulo();
        
        this.txtBusqueda = new WebTextField (15);
        this.txtBusqueda.setInputPrompt ( "Búsqueda" );
        this.txtBusqueda.setInputPromptFont ( this.txtBusqueda.getFont ().deriveFont ( Font.ITALIC ) );
        
        this.chbInactivos = new WebCheckBox("Inactivos");
        this.tblArticulos = new WebTable();
        this.tblStocks = new WebTable();
        
        this.btnAgregar = new WebButton("Agregar", new ImageIcon(getClass().getResource("/resources/img/add.png")));
        this.btnEditar = new WebButton("Editar", new ImageIcon(getClass().getResource("/resources/img/cart_edit.png")));
        this.btnCerrar = new WebButton("Cerrar", new ImageIcon(getClass().getResource("/resources/img/cancel.png")));
        cargarCategorias();
        
        add(new WebPanel(){
            {
                setBackground(Color.white);
                setLayout(new BorderLayout());
                add(new WebPanel(){
                    {
                        setLayout(new BorderLayout());
                        add(new WebLabel("Búsqueda"), BorderLayout.WEST);
                        add(FrmArticulos.this.txtBusqueda, BorderLayout.CENTER);
                        add(FrmArticulos.this.chbInactivos, BorderLayout.EAST);
                    }
                }, BorderLayout.NORTH);
                add(new WebPanel(){
                    {
                        add(new WebScrollPane(chbLstCategorias));
                    }
                }, BorderLayout.WEST);
                add(new WebPanel(){
                    {
                        buscar();
                        cargarStocks(-1);
                        add(new WebScrollPane(tblArticulos));
                    }
                }, BorderLayout.CENTER);
                add(new WebPanel(){
                    {
                        add(new WebScrollPane(tblStocks));
                    }
                }, BorderLayout.EAST);
                add(new WebPanel(){
                    {
                        setLayout(new FlowLayout(FlowLayout.RIGHT));
                        this.add(btnAgregar, btnEditar, btnCerrar);
                    }
                }, BorderLayout.SOUTH);
            } 
        });
        this.txtBusqueda.addActionListener((ActionEvent e) -> {
            buscar();
        });
        this.tblArticulos.addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent e){
                int row = tblArticulos.getSelectedRow();
                if(e.getClickCount() == 1) {
                    cargarStocks((int) tblArticulos.getModel().getValueAt(row, 0));
                }
            }
        });
        
        this.btnAgregar.addActionListener((ActionEvent e)->{
            FrmArticulo fa = new FrmArticulo(this, false);
            fa.setVisible(true);
        });
        
        this.btnEditar.addActionListener((ActionEvent e) -> {
            //Si no se ha seleccionado, devuelve -1, entonces carga por defecto el primer elemento
            int row = tblArticulos.getSelectedRow() == -1 ? 0: tblArticulos.getSelectedRow();
            FrmArticulo fa = new FrmArticulo(
                    this, 
                    false, 
                    (int) tblArticulos.getModel().getValueAt(row, 0));
            fa.setVisible(true);
        });
        
        this.btnCerrar.addActionListener((ActionEvent e)->{
            this.dispose();
        });
                
        this.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosed(WindowEvent evt){
                FrmPrincipal.bolFrmArticulos = false;
            }
        });
    }
    
    private void buscar(){
        try {            
            ArrayList<Articulo> articulos = this.ctrlArticulo.getArticulos_categorias(
                    null,
                    this.txtBusqueda.getText(),
                    this.chbInactivos.isSelected(),
                    getSelected());
            DefaultTableModel model = new DefaultTableModel();
            this.tblArticulos.setModel(model);
            model.addColumn("idArticulo");
            model.addColumn("Nombre");
            model.addColumn("Precio");
            articulos.stream().forEach((articulo) -> {
                model.addRow(new Object[]{
                    articulo.getIdArticulo(),
                    articulo.getNombre(),
                    Utilidades.setUpMoneda(articulo.getPrecioVenta())
                });
            });
            this.tblArticulos.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            this.tblArticulos.removeColumn(this.tblArticulos.getColumnModel().getColumn(0));
            Utilidades.alinearColumna_derecha(tblArticulos, "Precio");
            Utilidades.resizeColumnWidth(tblArticulos);
            this.tblArticulos.setEditable(false);
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(FrmArticulos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }    
    
    private ArrayList<Categoria> getSelected(){
        ArrayList<Categoria> categorias = new ArrayList<>();
        CheckBoxListModel model = this.chbLstCategorias.getCheckBoxListModel();
        for(int i=1; i < model.getSize(); i++){
            if(model.isCheckBoxSelected(i))
                categorias.add((Categoria) model.getElementAt(i).getUserObject());
        }
        return categorias;
    }
    
    private void cargarCategorias(){
        CheckBoxListModel model = new CheckBoxListModel();
        model.addCheckBoxElement("Todos");
        try {
            ctrlCategoria.getCategorias("", null).stream().forEach((cat) -> {
                model.addCheckBoxElement(cat);
            });
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(FrmArticulos.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        this.chbLstCategorias = new WebCheckBoxList(model);
    }
    
    public void cargarStocks(int idArticulo){
        try {
            DefaultTableModel model = new DefaultTableModel();
            this.tblStocks.setModel(model);
            model.addColumn("Almacén");
            model.addColumn("Stock");
            ArrayList<AlmacenArticulo> stocks = this.ctrlArticulo.getStocks(idArticulo, null);
            stocks.stream().forEach((stock)->{
                model.addRow(new Object[]{
                    stock.getAlmacen().getIdAlmacen(),
                    stock.getStock()
                });
            });
            Utilidades.resizeColumnWidth(this.tblStocks);
        } catch (SQLException | ClassNotFoundException ex) {
            Logger.getLogger(FrmArticulos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
